package com.stray.crawl.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.stray.crawl.model.CrawlPlan;
import com.stray.crawl.model.PlanField;
import com.stray.crawl.model.PlanUrl;
import com.stray.crawl.model.UrlParam;
import com.stray.crawl.model.dao.RegexPattern;

public class ModelUtils {

	public static CrawlPlan generateName(CrawlPlan plan) {
		String name = StringUtils.lowerCase(plan.getPlanGroup() + "-" + plan.getPlanCategory());
		plan.setName(name);

		return plan;
	}

	public static PlanUrl addUrl(CrawlPlan plan, String url) {
		return addUrl(plan, url, true);
	}

	public static PlanUrl addUrl(CrawlPlan plan, String url, boolean convertable) {
		List<PlanUrl> urls = plan.getUrls();

		if (urls == null) {
			urls = new ArrayList<PlanUrl>();
			plan.setUrls(urls);
		}

		PlanUrl u = new PlanUrl();

		u.setUrl(url);
		u.setConvertable(convertable);

		urls.add(u);

		return u;
	}

	public static void addParam(PlanUrl url, String name, String key, RegexPattern regex, char asRorC, boolean optional) {
		List<UrlParam> params = url.getParams();

		if (params == null) {
			params = new ArrayList<UrlParam>();
			url.setParams(params);
		}

		UrlParam p = new UrlParam();
		p.setName(name);
		p.setKey(key);
		p.setType(regex.toString());
		p.setAsRequestOrContent(String.valueOf(asRorC));
		p.setOptional(optional);

		params.add(p);
	}

	public static String convertFieldToColumn(String fieldName) {
		StringBuffer buf = new StringBuffer();

		for (int i = 0; i < fieldName.length(); i++) {
			if (Character.isUpperCase(fieldName.charAt(i))) {
				buf.append("_").append(Character.toLowerCase(fieldName.charAt(i)));
			} else {
				buf.append(fieldName.charAt(i));
			}
		}

		return buf.toString();
	}

	public static void addFields(CrawlPlan plan, String... exprs) {
		List<PlanField> fields = plan.getFields();

		if (fields == null) {
			fields = new ArrayList<PlanField>();
			plan.setFields(fields);
		}

		for (int i = 0; i < exprs.length - 1; i += 2) {
			String name = exprs[i];
			String expr = exprs[i + 1];

			PlanField f = new PlanField();
			f.setName(name);
			f.setQuery(expr);

			fields.add(f);
		}
	}

}